package com.fucking.great.context.plun.db;

import cn.hutool.db.*;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.handler.RsHandler;
import cn.hutool.db.sql.Query;
import cn.hutool.db.sql.Wrapper;
import cn.hutool.setting.Setting;
import com.fucking.great.context.exception.TxnRuntimeException;
import com.fucking.great.context.common.db.JDBCSession;
import com.fucking.great.context.plun.BasePlug;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class DbPlug extends BasePlug {
    public DbPlug(Map<String, String> config) {
        super(config, new String[]{
                JDBCSession.class.getName(),
                List.class.getName(),
                Entity.class.getName(),
                RsHandler.class.getName(),
                Query.class.getName(),
                "cn.hutool.db.sql.Condition.LikeType",
                Collection.class.getName(),
                Page.class.getName(),
                PageResult.class.getName(),
                SqlConnRunner.class.getName(),
                Wrapper.class.getName()
        });
    }

    @Override
    public Map<String, Object> beginUser() {
        Map<String, Object> stringObjectMap = super.beginUser();
        // 开启事务.
        for (Map.Entry<String, Object> stringObjectEntry : stringObjectMap.entrySet()) {
            Session session = (Session) stringObjectEntry.getValue();
            try {
                session.beginTransaction();
            } catch (SQLException throwables) {
                TxnRuntimeException.throwException("DB_Begin_Transaction",throwables);
            }
        }
        return stringObjectMap;
    }

    @Override
    protected void initUserPlunMap(Map<String, Object> userPlun) {
        Setting setting = Setting.create();
        Map<String, String> config = this.getConfig();
        setting.putAll(config);
//        String driver = setting.getStr("driver");
        //
        DSFactory dsFactory = DSFactory.create(setting);
        DataSource dataSource = dsFactory.getDataSource();
        // Session.create(dataSource); =》 这个报驱动找不到的错。
        userPlun.putIfAbsent("db",new JDBCSession( dataSource ));
    }

    @Override
    public void commit() {
        JDBCSession session = null;
        for (Object value : this.getAllUserPlun().values()) {
            session =  (JDBCSession) value;
            try {
                session.commit();
            } catch (SQLException throwables) {
                TxnRuntimeException.throwException("DB_BEGIN","DB组件,commit",throwables);
            }finally {
                session.close();
            }
        }
    }

    @Override
    public void quietRollback() {
        JDBCSession session = null;
        for (Object value : this.getAllUserPlun().values()) {
            session =  (JDBCSession) value;
            session.quietRollback();
            session.close();
        }
    }

}
